<template>
    <div class="e-form">
        <BillTop title="设备调动编辑" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="调动明细" name="planDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="随机工具及技术资料" name="technicalInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="变更历史" name="changeHistory" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData.handoverTransfer" label-width="200px" :rules="rules">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="调动编号：">
                                            <span>{{ formData.handoverTransfer.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="填报日期：" prop="billDate">
                                            <el-date-picker
                                                v-model="formData.handoverTransfer.billDate"
                                                type="date"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                :clearable="false"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="经办人：" prop="agenter">
                                            <el-input v-model="formData.handoverTransfer.agenter" readonly>
                                                <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="selectHandling"></i>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="调入机构：" prop="transferOrg">
                                            <el-input v-model="formData.handoverTransfer.transferOrg" readonly>
                                                <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="selectTransferOrg"></i>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="接收人：" prop="receiver">
                                            <el-input v-model="formData.handoverTransfer.receiver" readonly>
                                                <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="selectReceiver"></i>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{ statusLable(formData.handoverTransfer.state) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="租赁金额（不含税）：">
                                            <span>{{ formData.handoverTransfer.amount }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="租赁金额（含税）：">
                                            <span>{{ formData.handoverTransfer.leaseAmount }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                <el-col :span="12">
                                        <el-form-item label="税率%：">
                                            <el-input v-model="formData.handoverTransfer.tax"
                                            @blur="taxBlur"
                                            v-enter-integer2="{
                                                set:formData,
                                                val:'handoverTransfer',
                                                key:'tax'
                                            }">
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="税额（元）：">
                                            <el-input v-model="formData.handoverTransfer.taxAmount"
                                            :disabled="isDisabled"
                                            v-enter-float="{
                                                set:formData,
                                                val:'handoverTransfer',
                                                key:'taxAmount'
                                            }">
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="机构：">
                                            <span> {{formData.handoverTransfer.orgName}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item  label="备注信息：">
                                            <el-input type="textarea" v-model="formData.handoverTransfer.remarks" placeholder="请输入内容"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="planDetailCon" class="con">
                        <div class="tabs-title" id="planDetail">调动明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button  class="btn-greenYellow" @click="selectEquip">选择设备</el-button>
                                        <el-button  class="btn-delete" @click="deleteTransferList " v-if="isBatch[0].flag">批量删除</el-button>
                                    </div>
                                    <div class="batchBox" @click="batchOperation('planDetail')">
                                        <img class="batchicon" src="@/assets/piliang.png">
                                        <span class="batchfont">{{isBatch[0].batch}}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="errorMsg" v-if="errorMsg.length>0">
                                <span v-for="item,index in errorMsg" :key="index">
                                    {{item}}
                                </span>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="handoverTransferDtlListCopy"
                                border
                                style="width: 100%"
                                @selection-change="planTableSelect"
                                v-sortTable="{ 'tableData': handoverTransferDtlListCopy, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column fixed type="selection" width="55" align="center" v-if="isBatch[0].flag">
                                </el-table-column>
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row,$index }">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleTransferDelete(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="equipmentNo" label="设备编号" min-width="200" show-overflow-tooltip align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="originalNo"
                                    label="原始编号"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentName"
                                    label="设备名称"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="categoryName"
                                    label="设备类别"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="100"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="manufacturer"
                                    label="生产厂商"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="originalPlace"
                                    label="原在何地"
                                    min-width="280"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.originalPlace" readonly @input="curStateChange(row)">
                                            <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="selectOriginalPlace(row)"></i>
                                        </el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="leaseUnit"
                                    label="计时单位"
                                    width="160"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-select
                                            v-model="row.leaseUnit"
                                            placeholder="请选择计时单位"
                                            @input="curStateChange(row)"
                                        >
                                            <el-option
                                                v-for="(
                                                    item
                                                ) in timeUnitList"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.label"
                                            >
                                            </el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="leasePrice"
                                    label="租金单价（元）"
                                    width="150"
                                    align="right"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.leasePrice" clearable
                                        @input="curStateChange(row)"
                                        v-enter-float="{
                                            set: row,
                                            key: 'leasePrice'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="leaseTerm"
                                    label="租赁时间"
                                    width="130"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.leaseTerm" clearable
                                        @input="curStateChange(row)"
                                        v-enter-float="{
                                            set: row,
                                            key: 'leaseTerm'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="enterPrice"
                                    label="进场费（元）"
                                    width="130"
                                    align="right"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.enterPrice" clearable
                                        @input="curStateChange(row)"
                                        v-enter-float="{
                                            set: row,
                                            key: 'enterPrice'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="exitPrice"
                                    label="退场费（元）"
                                    width="130"
                                    align="right"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.exitPrice" clearable
                                        @input="curStateChange(row)"
                                        v-enter-float="{
                                            set: row,
                                            key: 'exitPrice'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="operatingSalary"
                                    label="操作手工资（元）"
                                    width="200"
                                    align="right"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.operatingSalary" clearable
                                        @input="curStateChange(row)"
                                        v-enter-float="{
                                            set: row,
                                            key: 'operatingSalary'
                                        }">></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="leaseAmount"
                                    label="租赁金额（元）"
                                    width="130"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="maintenanceUnit"
                                    label="维修费承担方"
                                    width="160"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-select v-model="row.maintenanceUnit" @input="curStateChange(row)">
                                            <el-option :value="0" label="调出机构"></el-option>
                                            <el-option :value="1" label="调入机构"></el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                 <el-table-column
                                    prop="maintainUnit"
                                    label="保养费承担方"
                                    width="160"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-select v-model="row.maintainUnit" @input="curStateChange(row)">
                                            <el-option :value="0" label="调出机构"></el-option>
                                            <el-option :value="1" label="调入机构"></el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="startTime"
                                    label="预计开始时间"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-date-picker type="date" placeholder="选择日期" v-model="row.startTime" style="width: 100%;" value-format="yyyy-MM-dd" @input="curStateChange(row)"></el-date-picker>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="handoverDate"
                                    label="交接日期"
                                    width="130"
                                    align="center"
                                    v-if="state === 2"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="验收情况"
                                    width="130"
                                    align="center"
                                    v-if="state === 2"
                                >
                                   <template>
                                        <el-button size="small" class="btn-blue"
                                            >查看</el-button
                                        >
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="exitStatus"
                                    label="退场状态"
                                    width="130"
                                    align="center"
                                    v-if="state === 2"
                                >
                                <template slot-scope="{ row }">
                                        <span>{{ row.exitStatus ? '已退场' : '未退场' }} </span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="technicalInfoCon" class="con">
                        <div class="tabs-title" id="technicalInfo">随机工具及技术资料</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button  class="btn-greenYellow" @click="technicalAdd">新增</el-button>
                                        <el-button  class="btn-delete" @click="deleteToolsList " v-if="isBatch[1].flag">批量删除</el-button>
                                    </div>
                                    <div class="batchBox" @click="batchOperation('technicalInfo')">
                                        <img class="batchicon" src="@/assets/piliang.png">
                                        <span class="batchfont">{{isBatch[1].batch}}</span>
                                    </div>
                                </div>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="toolsTable"
                                :data="facilityAttachmentToolsListCopy"
                                border
                                style="width: 100%"
                                @selection-change="toolsTableSelect"
                                v-sortTable="{ 'tableData': facilityAttachmentToolsListCopy, '_this': this, 'ref': 'toolsTable' }"
                            >
                                <el-table-column fixed type="selection" width="55" align="center" v-if="isBatch[1].flag">
                                </el-table-column>
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row,$index }">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleToolsDelete(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="name"
                                    label="名称"
                                    align="center"
                                    min-width="200"
                                    show-overflow-tooltip
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.name" clearable @input="curToolsStateChange(row)"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="specifications"
                                    label="规格型号"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.specifications" clearable @input="curToolsStateChange(row)"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.unit" clearable @input="curToolsStateChange(row)"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="number"
                                    label="数量"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.number" clearable
                                        @input="curToolsStateChange(row)"
                                        v-enter-float2="{
                                            set: row,
                                            key: 'number'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" bucketName="facilityconnect" />
                    </div>

                    <div id="changeHistoryCon" class="con">
                        <div class="tabs-title" id="changeHistory">变更历史</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                :data="changeHistoryTable"
                                border
                                ref="changeHistorySelect"
                                v-sortTable="{ 'tableData': changeHistoryTable, '_this': this, 'ref': 'changeHistorySelect' }"
                            >
                                <el-table-column fixed label="操作" width="100">
                                    <template slot-scope="{row}">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleDeleteHistory(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changeBillNo"  align="center" label="变更编号" min-width="200" show-overflow-tooltip class-name="blue-column">
                                    <template slot-scope="{ row }" >
                                        <span @click="tableDbShow(row)">{{row.changeBillNo}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="billDate"
                                    label="变更日期"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="orgName"
                                    label="机构"
                                    show-overflow-tooltip min-width="200"
                                    align="left"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="number"
                                    label="变更期数"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="state"
                                    label="状态"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{row}">
                                        <span>{{statusLable(row.state)}}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                billType="4012"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState" :state="formData.handoverTransfer.state" @exas="exas" :founderId="formData.handoverTransfer.founderId" />
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/purchaseAcceptance.js'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import { getCurrentUnitInfo, history } from '@/api/equip/handoverAudit.js'
import count from '@/api/equip/equipHandoverCount.js'
import { hideLoading, showLoading } from '@/utils/common'
import { selectName, selectReceiver, selectAllOrg, selectMoveEquipment } from '@/api/equip/popupCallback.js'
import { exas, saveAll, submitCommit } from '@/pages/equipment/components/auditHistory/equipCom.js'
export default {
    data () {
        return {
            res: '',
            isBatch: [
                {
                    flag: true,
                    batch: '进入批量管理'
                },
                {
                    flag: true,
                    batch: '进入批量管理'
                },
                {
                    flag: true,
                    batch: '进入批量管理'
                }
            ],
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            formData: {
                //设备调动基础信息
                handoverTransfer: {
                    'agenter': '',
                    'amount': 0,
                    'auditDate': '',
                    'auditor': '',
                    'auditorId': '',
                    'billDate': '',
                    'billId': '',
                    'billNo': '',
                    'changeBillNo': '',
                    'changeState': null,
                    'easId': '',
                    'founderId': '',
                    'founderName': '',
                    'gmtCreate': '',
                    'gmtModified': '',
                    'leaseAmount': 0,
                    'modifier': '',
                    'modifierId': '',
                    'nullifyCreated': '',
                    'nullifyCreator': '',
                    'nullifyCreatorId': '',
                    'nullifyDescription': '',
                    'nullifyReason': '',
                    'number': 0,
                    'orgId': '',
                    'orgName': '',
                    'receiver': '',
                    'recorder': '',
                    'recorderId': '',
                    'remarks': '',
                    'state': 0,
                    'tax': null,
                    'taxAmount': 0,
                    'transferOrg': '',
                    'transferOrgId': '',
                    'version': 0,
                    'workId': ''
                },
            },
            rules: {
                billDate: [
                    { required: true, message: '请选择填报日期', trigger: 'change' },
                ],
                agenter: [
                    { required: true, message: '请选择经办人', trigger: 'change'  },
                ],
                receiver: [
                    { required: true, message: '请选择接收人', trigger: 'change' },
                ],
                transferOrg: [
                    { required: true, message: '请选择调入机构', trigger: 'change' },
                ],
                managementUnit: [
                    { required: true, message: '请选择管理单位', trigger: 'change' },
                ],
            },
            billid: this.$route.query.billid,
            handoverTransferDtlList: [], //调动明细  传给后端
            handoverTransferDtlListCopy: [], //调动明细 前端显示
            planSelect: [], //调动明细选择项
            facilityAttachmentToolsList: [], //随机工具及技术资料 传后端
            facilityAttachmentToolsListCopy: [], //随机工具及技术资料 前端显示
            toolsSelect: [], //随机工具及技术资料选择项
            auditHistoryTable: [], //审核历史表格
            changeHistoryTable: [], //变更历史
            changeHistorySelect: [], //变更历史选择项
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
            currentRow: {}, //调动明细当前行数据
            currentToolsRow: {}, //随机工具当前行数据
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 4012,
                'freeNextUnitIndex': null,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 4012,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            isDisabled: false,
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            timeUnitList: state => state.equip.equipData.timeUnitList, //计时单位
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return obj ? obj.label : ''
            }
        },
        //当前单据状态
        state () {
            return this.formData.handoverTransfer.state
        },
        attachId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    created () {
        this.getDicValue()
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'planDetail', 'technicalInfo', 'attach', 'changeHistory', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setAuditParams']),
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setTimeUnitList')
        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //是否进入批量操作
        batchOperation (name) {
            switch(name) {
            case 'planDetail':
                this.isBatch[0].flag = !this.isBatch[0].flag
                if(this.isBatch[0].flag) {
                    this.isBatch[0].batch = '退出批量管理'
                    this.$refs.planTable.clearSelection()
                }else{
                    this.isBatch[0].batch = '进入批量管理'
                }
                break
            case 'technicalInfo':
                this.isBatch[1].flag = !this.isBatch[1].flag
                if(this.isBatch[1].flag) {
                    this.isBatch[1].batch = '退出批量管理'
                    this.$refs.toolsTable.clearSelection()
                }else{
                    this.isBatch[1].batch = '进入批量管理'
                }
                break
            }
        },
        //初始化数据
        init () {
            showLoading()
            Promise.all([
                this.getInfo(),
                this.getPlanList(),
                this.getTechnicalList(),
                this.getCurrentUnitInfo(),
                this.getAuditHistory(),
                this.getChangeHistory()
            ]).finally(() => {
                hideLoading()
            })
        },
        //获取基本信息
        getInfo () {
            const params = {
                id: this.billid,
            }
            request.equipMoveBaseInfo(params).then(res=>{
                this.formData.handoverTransfer = res.handoverTransfer
            })
        },
        //获取调动明细
        getPlanList () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.equipMovePlanInfo(params).then(res=>{
                this.handoverTransferDtlListCopy = []
                this.handoverTransferDtlList = res.handoverTransferDtlList
                res.handoverTransferDtlList.map(item=>{
                    this.handoverTransferDtlListCopy.push(item)
                })
            })
        },
        //获取随机工具及技术资料
        getTechnicalList () {
            const params = {
                transferId: this.billid,
            }
            request.equipMovePlanTechnical(params).then(res=>{
                this.facilityAttachmentToolsListCopy = []
                this.facilityAttachmentToolsList = res.facilityAttachmentToolsList
                res.facilityAttachmentToolsList.map(item=>{
                    this.facilityAttachmentToolsListCopy.push(item)
                })
            })
        },
        //获取状态按钮
        getCurrentUnitInfo () {
            getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            history(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //变更历史查询
        getChangeHistory () {
            const params = {
                billId: this.billid,
            }
            request.getMoveChangeHistory(params).then(res=>{
                this.changeHistoryTable = res
            })
        },
        //========基础信息============
        /**税额 = 租赁金额（不含税）*税率 */
        taxBlur () {
            this.isDisabled  = this.formData.handoverTransfer.tax == 0 ? true : false
            this.formData.handoverTransfer.taxAmount = count.onTaxAmount(+this.formData.handoverTransfer.amount, +this.formData.handoverTransfer.tax)
            this.onLeaseAmount()
        },
        //租赁金额(含税) = 租赁金额（不含税）+税额
        onLeaseAmount () {
            this.formData.handoverTransfer.leaseAmount = count.onLeaseAmount(+this.formData.handoverTransfer.amount, +this.formData.handoverTransfer.taxAmount)
        },
        //选择经办人 (选择本机构用户)
        selectHandling () {
            selectName().then(res=>{
                this.formData.handoverTransfer.agenter = res[0].userName
            })
        },
        //选择调入机构
        selectTransferOrg () {
            selectAllOrg({ 'title': '选择调入机构' }).then(res=>{
                this.formData.handoverTransfer.transferOrg = res[0].orgName
                this.formData.handoverTransfer.transferOrgId = res[0].orgId
            })
        },
        //选择接入人
        selectReceiver () {
            if(!this.formData.handoverTransfer.transferOrg) {
                this.clientPop('err', '请先选择调入机构！')
                return
            }else{
                selectReceiver(this.formData.handoverTransfer.transferOrgId).then(res=>{
                    this.formData.handoverTransfer.receiver = res[0].userName
                    this.formData.handoverTransfer.recorderId = res[0].userId
                })
            }
        },
        //==========调动明细==============
        /**选择设备 */
        selectEquip () {
            let ids = []
            ids = this.handoverTransferDtlListCopy.map(x=>x.accountId)
            let json = {
                'flag': false,
                'ids': ids,
                'params': {
                    'orgId': this.formData.handoverTransfer.orgId,
                    'states': []
                }
            }
            selectMoveEquipment(json).then(res=>{
                this.itemObj = {}
                this.itemObjCopy = {}
                res.forEach(item=>{
                    let obj = {
                        'acceptanceDtlId': '',
                        'accountId': '',
                        'billId': this.billid,
                        'billNo': '',
                        'categoryId': '',
                        'categoryName': '',
                        'changeType': 1,
                        'enterPrice': null,
                        'equipmentId': '',
                        'equipmentName': '',
                        'equipmentNo': '',
                        'exitPrice': null,
                        'exitState': true,
                        'gmtCreate': '',
                        'gmtModified': '',
                        'handoverDate': '',
                        'isMaintancence': null,
                        'leaseAmount': null,
                        'leasePrice': null,
                        'leaseTerm': null,
                        'leaseUnit': '',
                        'maintainUnit': '',
                        'maintenanceUnit': '',
                        'manufacturer': '',
                        'oneLevelCategoryId': '',
                        'oneLevelCategoryName': '',
                        'operatingSalary': null,
                        'originalNo': '',
                        'originalPlace': this.formData.handoverTransfer.orgName,
                        'originalPlaceId': '',
                        'productionDate': '',
                        'productionNo': '',
                        'purchasePrice': null,
                        'specificationModel': '',
                        'startTime': '',
                        'transferDtlId': '',
                        'unit': '',
                        'receiveId': '',
                        ...item
                    }
                    this.handoverTransferDtlListCopy.push(obj)
                    this.handoverTransferDtlList.push(obj)
                })
                this.handoverTransferDtlListCopy = this.handoverTransferDtlListCopy.reduce((item, next)=>{
                    if(!this.itemObjCopy[next.accountId]) {
                        item.push(next)
                        this.itemObjCopy[next.accountId] = true
                    }
                    return item
                }, [])
                this.handoverTransferDtlList = this.handoverTransferDtlList.reduce((item, next)=>{
                    if(next.changeType == -1) {
                        item.push(next)
                    }else{
                        if(!this.itemObj[next.accountId]) {
                            item.push(next)
                            this.itemObj[next.accountId] = true
                        }
                    }
                    return item
                }, [])
            })
        },
        /**选择原在何地 */
        selectOriginalPlace (row) {
            selectAllOrg({ 'title': '选择组织机构' }).then(res=>{
                row.originalPlace = res[0].orgName
                row.originalPlaceId = res[0].orgId
                if (row.transferDtlId) {
                    row.changeType = 2
                }
            })
        },

        //判断当前状态是否已修改
        curStateChange (row) {
            this.currentRow = row
            if (row.transferDtlId) {
                this.currentRow.changeType = 2
            }
            this.onAmount(row)
        },
        //租赁金额 = 租赁时间*租金单价（元）+进场费（元）+退场费（元）+操作手工资（元） 保留两位小数
        onAmount (row) {
            row.leaseAmount = count.onAmount(+row.leaseTerm, +row.leasePrice, +row.enterPrice, +row.exitPrice, +row.operatingSalary)
            this.onUpCollect()
        },
        //租赁金额（不含税） = 明细获取租赁金额向上汇总 保留两位小数
        onUpCollect () {
            this.formData.handoverTransfer.amount = null
            this.formData.handoverTransfer.amount = count.onUpCollect(this.handoverTransferDtlList)
            this.taxBlur()
        },
        //单个调动明细表格删除
        handleTransferDelete (row, $index) {
            this.clientPop('info', this.oneDeleteErr, ()=>{
                let length = this.errorMsg.length
                if(row.transferDtlId) {
                    this.$set(this.handoverTransferDtlList[$index], 'changeType', -1)
                    this.handoverTransferDtlListCopy.splice($index, 1)
                }else{
                    this.handoverTransferDtlList.splice($index, 1)
                    this.handoverTransferDtlListCopy.splice($index, 1)
                }
                if (length > 0 ) {
                    this.verifyMoveTable()
                }
                this.onUpCollect()
            })
        },
        //获取调动明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //删除调动明细列表
        deleteTransferList () {
            const length = this.planSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.delete
                )
            }
        },
        delete () {
            let length = this.errorMsg.length
            this.planSelect.filter(row=>{
                this.handoverTransferDtlListCopy.map((x, index)=>{
                    if(row == x ) {
                        this.handoverTransferDtlListCopy.splice(index, 1)
                    }
                })
                if(row.transferDtlId) {
                    const index = this.handoverTransferDtlList.findIndex(item=>{
                        return item.transferDtlId == row.transferDtlId
                    })
                    this.$set(this.handoverTransferDtlList[index], 'changeType', -1)
                }else{
                    this.handoverTransferDtlList.map((x, index)=>{
                        if(row == x ) {
                            this.handoverTransferDtlList.splice(index, 1)
                        }
                    })
                }
                if (length > 0 ) {
                    this.verifyMoveTable()
                }
                this.onUpCollect()
                this.$refs.planTable.clearSelection()
            })
        },
        //调动明细非空验证
        verifyMoveTable () {
            return  new Promise((resolve, reject)=>{
                this.errorMsg = []
                this.handoverTransferDtlListCopy.forEach((item, index)=>{
                    if(item.changeType !== -1) {
                        if(item.originalPlace == null || item.originalPlace == '') {
                            let str = `请填写第 ${index + 1} 行的（原在何地）`
                            this.errorMsg.push(str)
                        }
                        if(item.leaseUnit == null || item.leaseUnit == '') {
                            let str = `请填写第 ${index + 1} 行的（计时单位）`
                            this.errorMsg.push(str)
                        }
                        if(item.leasePrice == null || item.leasePrice == '') {
                            let str = `请填写第 ${index + 1} 行的（租金单价（元））`
                            this.errorMsg.push(str)
                        }
                        if(item.leaseTerm == null || item.leaseTerm == '') {
                            let str = `请选择第 ${index + 1} 行的（租赁时间）`
                            this.errorMsg.push(str)
                        }
                        if(item.maintenanceUnit != 0 && item.maintenanceUnit != 1) {
                            let str = `请选择第 ${index + 1} 行的（维修费承担方）`
                            this.errorMsg.push(str)
                        }
                        if(item.maintainUnit != 0 && item.maintainUnit != 1) {
                            let str = `请选择第 ${index + 1} 行的（保养费承担方）`
                            this.errorMsg.push(str)
                        }
                        if(item.startTime == null || item.startTime == '') {
                            let str = `请选择第 ${index + 1} 行的（预计开始时间）`
                            this.errorMsg.push(str)
                        }
                    }
                })
                if(this.errorMsg.length > 0) {
                    reject()
                }else{
                    resolve()
                }
            })
        },
        //==============随机工具及技术资料===========
        /**添加一随机工具 */
        technicalAdd () {
            let obj = {
                'attachmentToolsId': '',
                'billId': this.billid,
                'billNo': '',
                'changeType': 1,
                'name': '',
                'number': null,
                'specifications': '',
                'unit': ''
            }
            this.facilityAttachmentToolsList.push(obj)
            this.facilityAttachmentToolsListCopy.push(obj)
        },
        //判断当前状态是否已修改
        curToolsStateChange (row) {
            if (row.attachmentToolsId) {
                this.currentToolsRow = row
                this.currentToolsRow.changeType = 2
            }
        },
        //单个随机工具表格删除
        handleToolsDelete (row, $index) {
            this.clientPop('info', this.oneDeleteErr, ()=>{
                if(row.attachmentToolsId) {
                    this.$set(this.facilityAttachmentToolsList[$index], 'changeType', -1)
                    this.facilityAttachmentToolsListCopy.splice($index, 1)
                }else{
                    this.facilityAttachmentToolsList.splice($index, 1)
                    this.facilityAttachmentToolsListCopy.splice($index, 1)
                }
            })
        },
        //获取随机工具表格的选择项
        toolsTableSelect (selection) {
            this.toolsSelect = selection
        },
        //批量删除随机工具
        deleteToolsList () {
            const length = this.toolsSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.deleteTools
                )
            }
        },
        deleteTools () {
            this.toolsSelect.filter(row=>{
                this.facilityAttachmentToolsListCopy.map((x, index)=>{
                    if(row == x ) {
                        this.facilityAttachmentToolsListCopy.splice(index, 1)
                    }
                })
                if(row.attachmentToolsId) {
                    const index = this.facilityAttachmentToolsList.findIndex(item=>{
                        return item.attachmentToolsId == row.attachmentToolsId
                    })
                    this.$set(this.facilityAttachmentToolsList[index], 'changeType', -1)
                }else{
                    this.facilityAttachmentToolsList.map((x, index)=>{
                        if(row == x ) {
                            this.facilityAttachmentToolsList.splice(index, 1)
                        }
                    })
                }
                this.$refs.toolsTable.clearSelection()
            })
        },
        //取消
        handleClose () {
            this.$router.replace('/equipMoveList')
        },
        //更新基础信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.form.validate(valid => {
                    if(valid) {
                        request.equipMoveUpdate(this.formData).then(()=>{
                            resolve()
                        }).catch(err=>{
                            reject(err)
                            this.setError('baseInfo')
                        })
                    }else{
                        reject()
                        this.setError('baseInfo')
                        return false
                    }
                })
            })
        },
        //更新设备调动明细
        updateDetailInfo () {
            return new Promise((resolve, reject)=>{
                this.verifyMoveTable().then(()=>{
                    request.updateEquipMoveDtl(this.handoverTransferDtlList).then(()=>{
                        resolve()
                    }).catch(err=>{
                        reject(err)
                        this.setError('planDetail')
                    })
                }).catch(err=>{
                    this.setError('planDetail')
                    reject(err)
                })

            })
        },
        //更新随机工具及技术资料
        updateToolsInfo () {
            return new Promise((resolve, reject)=>{
                request.updateEquipToolsDtl(this.facilityAttachmentToolsList).then(()=>{
                    resolve()
                }).catch(err=>{
                    reject(err)
                    this.setError('technicalInfo')
                })
            })
        },
        //保存全部数据
        saveAll () {
            this.errorList = []
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateDetailInfo(),
                    this.updateToolsInfo()
                ]
            }
            saveAll(this, requestFn)
        },
        //保存并提交
        submitCommit () {
            if(this.handoverTransferDtlListCopy.length === 0) {
                let str = '计划明细不能空！'
                this.errorMsg.push(str)
                this.setError('planDetail')
                this.scorllError()
                return
            }
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateDetailInfo(),
                    this.updateToolsInfo()
                ]
            }
            submitCommit(this, requestFn, 1)
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return []
            }
            exas(arg, this, requestFn, 1)
        },
        //删除单据
        deleteBills () {
            let billIds = []
            billIds.push(this.billid)
            this.clientPop('info', this.oneDeleteErr, ()=>{
                request.equipMoveDelete(billIds).then(()=>{
                    this.clientPop('suc', '删除成功', this.handleClose)
                })
            })
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}

</style>
